#include "virtualcross.h"

#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QTcpServer>
//#include "ui_virtualcross.h"
#include <QJsonDocument>
#include <QPainter>
#include <QRandomGenerator>
#include <QTcpSocket>
#include <QTimer>

VirtualCross::VirtualCross(const int &id, QWidget *parent) :
    QWidget(parent),
    //ui(new Ui::VirtualCross),
    id(id)
{
   // ui->setupUi(this);

    // 初始化随机数生成器
    auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    srand(static_cast<unsigned int>(seed));

    // 初始化信号灯
    list_transLamp.append({Qt::red, 25});
    list_transLamp.append({Qt::green, 25});
    //list_transLamp.append({Qt::red, 25});

    // 初始化定时器
    timer = new QTimer(this);
    timer->setInterval(1000);
    connect(timer, &QTimer::timeout, this, &VirtualCross::slot_sendState);
    timer->start();

    // 连接到服务器
    socket.connectToHost("127.0.0.1", 10086);
    connect(&socket, &QTcpSocket::stateChanged, this, &VirtualCross::slot_stateChanged);
}

VirtualCross::~VirtualCross()
{
    delete ui;
}

void VirtualCross::slot_sendState()
{
    qDebug() << "Sending state for cross" << id;
    sendState();
}

void VirtualCross::sendState()
{
    if (socket.state() == QAbstractSocket::ConnectedState) {
        QJsonObject obj;
        obj.insert("code", 30003); // 自发送路口状态
        obj.insert("id", id);

        QJsonArray lamps;
        for (auto &lamp : list_transLamp) {
            QJsonObject lampObj;
            lampObj.insert("color", lamp.color.name());
            lampObj.insert("count", lamp.count);
            lamps.append(lampObj);
        }
        obj.insert("lamps", lamps);

        socket.write(QJsonDocument(obj).toJson());

        // 更新信号灯状态
        for (auto &lamp : list_transLamp) {
            if (lamp.count > 0) {
                lamp.count--;
            } else {
                lamp.count = 25; // 重置计数
                if (lamp.color == Qt::red) {
                    lamp.color = Qt::green;
                } else {
                    lamp.color = Qt::red;
                }
            }
        }
    }
}

void VirtualCross::slot_stateChanged(QAbstractSocket::SocketState state)
{
    if (state == QAbstractSocket::UnconnectedState) {
        qDebug() << "连接失败，正在尝试重新连接";
        socket.connectToHost("127.0.0.1", 10086);
    } else if (state == QAbstractSocket::ConnectedState) {
        qDebug() << "连接成功";
    }
}

void VirtualCross::slot_readyRead()
{
    QByteArray data = socket.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (!doc.isNull() && doc.isObject()) {
        QJsonObject obj = doc.object();
        if (obj.contains("code")) {
            int code = obj.value("code").toInt();
            if (code == 10101) { // 使所有信号灯变为全红
                setAllRed();
            }
        }
    }
}

void VirtualCross::setAllRed()
{
    // 将所有信号灯设置为红色
    for (auto &lamp : list_transLamp) {
        lamp.color = Qt::red;
        lamp.count = 0; // 重置计数
    }
}
